// UdpClient.cc文件
#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

// 格式为：udpclient server_ip server_port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage:" << argv[0] << " server_ip server_port" << std::endl;
        return 1;
    }
    std::string server_ip = argv[1];
    uint16_t server_port = std::stoi(argv[2]);

    // 1.创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cout << "client创建套接字失败" << std::endl;
        return 2;
    }
    // 2.bind,但不需要显示的bind

    // 填写服务器信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server)); // 先请0
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);                  // 主机转网络
    server.sin_addr.s_addr = inet_addr(server_ip.c_str()); // ip转4字节，4字节转网络序列

    while (true)
    {
        // 3.发消息
        std::string input;
        std::cout << "Please Enter# ";
        std::getline(std::cin, input); // 从输入流获取到input里
        sendto(sockfd, input.c_str(), input.size(), 0, (struct sockaddr *)&server, sizeof(server));

        // 4.收消息
        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int m = recvfrom(sockfd, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&peer, &len);
        if(m > 0)
        {
            buffer[m] = 0;
            std::cout << buffer << std::endl;
        }
    }

    return 0;
}